package com.campfire.intelligentsecurity.config;

import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import com.campfire.intelligentsecurity.business.service.CameraControlService;
import com.campfire.intelligentsecurity.business.service.TEventVideoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class ApplicationRunner implements org.springframework.boot.ApplicationRunner {

    protected final Logger LOG = LoggerFactory.getLogger(getClass());

    @Autowired
    CameraControlService cameraControlService;
    @Autowired
    TEventVideoService tEventVideoService;
    @Autowired
    Environment environment;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        cameraControlService.updFlag(0);//首轮启动重置轮巡状态
        Map<String, Object> map = tEventVideoService.getTask("lunxun");
        LOG.info("获取人员闯入轮巡配置：{}",map==null?null:map.toString());
        String cron = map.get("cron") == null ? "0 0 */1 * * ?" : map.get("cron").toString();
        String status = map.get("status") == null ? "true" : map.get("status").toString();
        LOG.info("获取云台控制token");
        cameraControlService.GetToken();
        /*if ("true".equals(status)){
            cameraControlService.lunxun();
        }*/
        CronUtil.schedule("0 */20 * * * ?", new Task() {
            @Override
            public void execute() {
                LOG.info("获取云台控制token");
                cameraControlService.GetToken();
            }
        });


        //0 0 */2 * * ?   //     */50 * * * * ?   //0 0 */1 * * ?
        CronUtil.schedule(map.get("task").toString(),cron, new Task() {
            @Override
            public void execute() {
                Map<String, Object> dataMap = tEventVideoService.getTask("lunxun");
                String state = dataMap.get("status") == null ? "true" : dataMap.get("status").toString();
                if ("true".equals(state)) {
                    //未在轮巡中，则启动轮巡
                    if (dataMap.get("flag").toString().equals("0")){
                        cameraControlService.lunxun();
                    }else{
                        LOG.info("当前轮巡还未结束 -> 等待下次定时轮巡");
                    }
                }
            }
        });
        CronUtil.setMatchSecond(true);
        CronUtil.start();
        LOG.info("定时任务启动完成");
    }


}
